package com.yxhl.zoume.core.main.ui.Fragment;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.core.main.info.SupportUpdateAppType;
import com.yxhl.zoume.core.main.ui.event.UpdateAppEvent;
import com.yxhl.zoume.core.main.ui.service.UpdateAppService;
import com.yxhl.zoume.data.http.rest.response.login.CheckUpdateResponse;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.domain.interactor.ZMEventSubscriber;
import com.yxhl.zoume.utils.AppInfoUtils;
import com.yxhl.zoume.utils.NetworkUtils;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.StorageUtils;
import com.yxhl.zoume.utils.ZMDialog;
import com.yxhl.zoume.utils.permission.PermissionHelper;

/**
 * created by sugarya
 */
public class UpdateAppDialogFragment extends DialogFragment {

    private static final String TAG = "UpdateAppDialogFra";

    private CheckUpdateResponse mCheckUpdateResponse;

    private Activity mActivity;

    public UpdateAppDialogFragment() {
        // Required empty public constructor
    }

    public static UpdateAppDialogFragment newInstance(CheckUpdateResponse checkUpdateResponse) {

        Bundle args = new Bundle();
        args.putSerializable(UIConstants.HomePage.ARGUMENT_KEY_CHECK_UPDATE_APP_VERSION, checkUpdateResponse);
        UpdateAppDialogFragment fragment = new UpdateAppDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleArguments();

    }

    private void handleArguments() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mCheckUpdateResponse = (CheckUpdateResponse) arguments.getSerializable(UIConstants.HomePage.ARGUMENT_KEY_CHECK_UPDATE_APP_VERSION);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        MaterialDialog dialog = null;
        String updateContent = mCheckUpdateResponse.getUpdateContent();
        int supportUpdateType = mCheckUpdateResponse.getSupportUpdateType();
        switch (supportUpdateType) {
            case SupportUpdateAppType.UPDATE_FORCE:
                dialog = new ZMDialog.Builder(mActivity)
                        .setTitle(getString(R.string.dialog_update_app_title))
                        .setMessage(updateContent)
                        .setPositiveMessage(getString(R.string.dialog_update_app_positive))
                        .setNegativeMessage(getString(R.string.dialog_update_app_neutral))
                        .setPositiveClickEvent(new ZMEventSubscriber() {
                            @Override
                            public void onNext(Object o) {
                                super.onNext(o);
                                navigateMobileBrowser();
                            }
                        })
                        .setNegativeClickEvent(new ZMEventSubscriber() {
                            @Override
                            public void onNext(Object o) {
                                super.onNext(o);
                                neutralClickHandler();
                            }
                        })
                        .builder();
                break;
            case SupportUpdateAppType.UPDATE_NORMAL:
                dialog = new ZMDialog.Builder(mActivity)
                        .setTitle(getString(R.string.dialog_update_app_title))
                        .setMessage(updateContent)
                        .setPositiveMessage(getString(R.string.dialog_update_app_positive))
                        .setNeutralMessage(getString(R.string.dialog_update_app_neutral))
                        .setNegativeMessage(getString(R.string.dialog_cancel))
                        .setPositiveClickEvent(new ZMEventSubscriber() {
                            @Override
                            public void onNext(Object o) {
                                super.onNext(o);
                                navigateMobileBrowser();
                            }
                        })
                        .setNeutralClickEvent(new ZMEventSubscriber() {
                            @Override
                            public void onNext(Object o) {
                                super.onNext(o);
                                neutralClickHandler();
                            }
                        })
                        .setNegativeClickEvent(new ZMEventSubscriber() {
                        })
                        .builder();
                break;
        }

        return dialog;
    }

    /**
     * 开始更新App版本
     */
    private void updateApp(Activity activity) {
        if (NetworkUtils.getInstance(activity).isConnected()) {
            if (PermissionHelper.checkWriteExternalStorage(activity)) {
                startUpdateAppService(activity);
            } else {
                RxBus.getInstance().send(new UpdateAppEvent());
            }
        } else {
            PromptUtils.showShort(activity, activity.getString(R.string.network_not_available));
        }
    }

    public void startUpdateAppService(Activity activity) {
        //判断手机存储卡容量是否够用,单位MB
        long sdFreeSize = StorageUtils.getSDFreeSize();
//        if(sdFreeSize > DataConstants.APK_PACKAGE_SIZE){
        Intent intent = new Intent(activity, UpdateAppService.class);
        String downloadUrl = mCheckUpdateResponse.getFileUrl();
        intent.putExtra(UIConstants.HomePage.INTENT_KEY_UPDATE_APP, downloadUrl);

        activity.startService(intent);
//        }else{
//            PromptUtils.showShort(activity,getString(R.string.update_app_external_storage_capacity_lack));
//        }
    }

    @Override
    public void dismiss() {
        int supportUpdateType = mCheckUpdateResponse.getSupportUpdateType();
        switch (supportUpdateType) {
            case SupportUpdateAppType.UPDATE_FORCE:
                System.exit(0);
                break;
            default:
                super.dismiss();
        }
    }

    /**
     * 点击去应用市场响应事件处理
     */
    private void neutralClickHandler() {
        Uri uri = Uri.parse("market://details?id=" + AppInfoUtils.getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PackageManager pm = getContext().getPackageManager();
        ActivityInfo activityInfo = intent.resolveActivityInfo(pm, PackageManager.MATCH_DEFAULT_ONLY);
        if (activityInfo != null) {
            startActivity(intent);
        } else {
            navigateMobileBrowser();
        }
    }

    /**
     * 跳转到浏览器下载APK包
     */
    private void navigateMobileBrowser() {
        String url = mCheckUpdateResponse.getFileUrl();
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);

            PackageManager pm = getContext().getPackageManager();
            ActivityInfo activityInfo = intent.resolveActivityInfo(pm, PackageManager.MATCH_DEFAULT_ONLY);
            if (activityInfo != null) {
                startActivity(intent);
            } else {
                updateApp(mActivity);
            }
        }
    }
}
